package com.asm.repository;

import com.asm.entity.sys.Contract;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Map;

/**
 * @author morningbear
 * @date 2019/7/11
 */
@Repository
public interface ContractRepository extends JpaRepository<Contract, Long> {

  /**
   * 根据合同编号查询合同
   *
   * @param id 合同编号
   * @return 合同信息
   */
  @Query("select c from Contract c where c.id=:id and c.isDel=false")
  Contract findContractById(@Param("id") Long id);

  /**
   * 查询与传入合同名称相同的所有合同信息
   *
   * @param contractName 合同名称
   * @param page 分页对象
   * @return 返回合同名称相同的所有合同
   */
  Page<Contract> findByContractName(String contractName, Pageable page);

  /**
   * 查询所有的合同信息
   *
   * @param of 分页请求
   * @return 所有合同信息
   */
  @Query("select c from Contract c where c.isDel=false ")
  Page<Contract> findAll(PageRequest of);

  /**
   * 查询所有合同信息
   *
   * @param pageable 分页
   * @return 合同信息
   */
  @Query("select new Map(c.id as contractId,b.sellId as sellId,b.customerId as customerId,cc.spotId as spotId,c.contractDate as contractDate,c.contractEndDate as contractEndDate) from Contract c inner " +
          "join ContractContain cc on c.id=cc.contractId inner join Book b on c.id=b.contractId where c.isDel=false")
  Page<Map<String, Object>> findAllContractMsgs(Pageable pageable);

  /**
   * 根据业务员编号查询合同信息
   *
   * @param sellId   业务员编号
   * @param pageable 分页
   * @return 合同信息
   */
  @Query("select new Map(c.id as contractId,b.sellId as sellId,b.customerId as customerId,cc.spotId as spotId,c.contractDate as contractDate,c.contractEndDate as contractEndDate) from Contract c inner " +
          "join ContractContain cc on c.id=cc.contractId inner join Book b on c.id=b.contractId where b.sellId=?1")
  Page<Map<String, Object>> findContractMsgsBySellId(Long sellId, Pageable pageable);

  /**
   * 根据顾客编号查询合同信息
   *
   * @param customerId 顾客编号
   * @param pageable   分页
   * @return 合同信息
   */
  @Query("select new Map(c.id as contractId,b.sellId as sellId,b.customerId as customerId,cc.spotId as spotId,c.contractDate as contractDate,c.contractEndDate as contractEndDate) from Contract c inner " +
          "join ContractContain cc on c.id=cc.contractId inner join Book b on c.id=b.contractId where b.customerId=?1")
  Page<Map<String, Object>> findContractMsgsByCustomerId(Long customerId, Pageable pageable);
}
